package top.ochiamalu.aioj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.ochiamalu.aioj.domain.dto.oauth.OAuthUserDTO;
import top.ochiamalu.aioj.domain.entity.OAuth;
import top.ochiamalu.aioj.domain.vo.user.UserLoginVO;
import top.ochiamalu.aioj.enums.OAuthTypeEnum;
import top.ochiamalu.aioj.mapper.OAuthMapper;
import top.ochiamalu.aioj.oauth.OAuthPlatformFactory;
import top.ochiamalu.aioj.service.OAuthService;

import java.io.IOException;

/**
 * 授权服务实施
 *
 * @author ochiamalu
 * @date 2025/03/12
 */
@Service
@RequiredArgsConstructor
public class OAuthServiceImpl extends ServiceImpl<OAuthMapper, OAuth>
        implements OAuthService {

    private final OAuthPlatformFactory platformFactory;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO authGithub(String code) throws IOException {
        return platformFactory.getPlatform("github").auth(code);
    }

    @Override
    public OAuthUserDTO getGithubUser(String code) throws IOException {
        return platformFactory.getPlatform("github").getUser(code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO bindGithub(Long userId, OAuthUserDTO githubUser) {
        return platformFactory.getPlatform("github").bind(userId, githubUser);
    }

    @Override
    public boolean isGithubBound(Long userId) {
        return platformFactory.getPlatform("github").isBound(userId);
    }

    @Override
    public boolean unbindGithub(Long userId) {
        return platformFactory.getPlatform("github").unbind(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO authGitee(String code) throws IOException {
        return platformFactory.getPlatform("gitee").auth(code);
    }

    @Override
    public OAuthUserDTO getGiteeUser(String code) throws IOException {
        return platformFactory.getPlatform("gitee").getUser(code);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO bindGitee(Long userId, OAuthUserDTO giteeUser) {
        return platformFactory.getPlatform("gitee").bind(userId, giteeUser);
    }

    @Override
    public boolean isGiteeBound(Long userId) {
        return platformFactory.getPlatform("gitee").isBound(userId);
    }

    @Override
    public boolean unbindGitee(Long userId) {
        return platformFactory.getPlatform("gitee").unbind(userId);
    }

    @Override
    public OAuth getByTypeAndOpenId(OAuthTypeEnum type, String openId) {
        return lambdaQuery()
                .eq(OAuth::getLoginType, type.getValue())
                .eq(OAuth::getOpenId, openId)
                .one();
    }
}
